package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.search.vos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
@Transactional
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {
    @Autowired
    private Configuration configuration; //freemarker
    @Autowired
    private FileStorageService fileStorageService; // minio
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate; //kafkatemplate对象

    /**
     * 基于freekmarer模板引擎生成静态的html页面,并且将页面上传到minio中,同时回填ap_article表中的article_id字段
     *
     * @param apArticle
     * @param content
     */
    @Override
    @Async
    public void buildStaticArticleToMinIO(ApArticle apArticle, String content) {
        //1.入参校验
        if (apArticle == null || StringUtils.isEmpty(content)) {
            return;
        }
        try {
            //2.读取页面模板
            Template template = configuration.getTemplate("article.ftl");
            //3.准备数据模型
            Map<String, Object> dateModel = new HashMap<>();
            dateModel.put("content", JSON.parseArray(content));

            //4.合成
            StringWriter out = new StringWriter();
            template.process(dateModel, out);

            //5.上传到minio
            InputStream in = new ByteArrayInputStream(out.toString().getBytes());
            String urlPath =
                    fileStorageService.uploadHtmlFile("", UUID.randomUUID() + ".html", in);

            //6.将返回的页面url更新到数据库表中
            apArticleMapper.update(apArticle, Wrappers.<ApArticle>lambdaUpdate()
                    .eq(ApArticle::getId, apArticle.getId())
                    .set(ApArticle::getStaticUrl, urlPath));


            /// TODO 发送消息到kafka中,搜索微服务监听消费同步对应的文章到ES中
//            createArticleESIndex(apArticle, content, urlPath);
            //构建SearchArticleVo对象
            SearchArticleVo vo = SearchArticleVo.builder()
                    .id(apArticle.getId())
                    .title(apArticle.getTitle())
                    .publishTime(apArticle.getPublishTime())
                    .layout(Integer.valueOf(apArticle.getLayout()))
                    .authorId(apArticle.getAuthorId())
                    .authorName(apArticle.getAuthorName())
                    .images(apArticle.getImages())
                    .staticUrl(urlPath)
                    .content(content)
                    .build();
            //发消息到kafka
            kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(vo));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    /**
//     * 发送kafka消息,ES消费更新索引库
//     *
//     * @param apArticle
//     * @param content
//     * @param urlPath
//     */
//    private void createArticleESIndex(ApArticle apArticle, String content, String urlPath) {
//        SearchArticleVo vo = new SearchArticleVo();
//        BeanUtils.copyProperties(apArticle, vo);
//        vo.setContent(content);
//        vo.setStaticUrl(urlPath);
//        //向kafka发送消息
//        kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(vo));
//    }
}
